package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/blogDetails")
public class BlogDetails extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    // 接收客户端请求，跳转到博客详情页
    // 约定 get /blogDetails
    // 格式 application/json
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取 blogId
        req.setCharacterEncoding("utf8");
        String blogId = req.getParameter("blogId");
        System.out.println(blogId);
        if(blogId == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("请求中没有 blogId");
            return;
        }
        // 2. 根据 blogId 获取 blog
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.getBlogByBlogId(Integer.parseInt(blogId));
        if(blog == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("没有找到 blogId");
            return;
        }
        // 3. 调用 jackson API , 构建 json 字符串
        String respJson = objectMapper.writeValueAsString(blog);
        System.out.println("respJson: " + respJson);
        // 4. 返回响应
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);
    }
}
